package com.tenclass.common.interceptor.exception;

import cn.ilanxin.common.error.ContextExceptionV2;
import cn.ilanxin.common.type.v2.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 默认全局异常处理器
 * @author YIJIUE
 * @since 1.1.5
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    /**
     * 业务异常拦截
     */
    @ExceptionHandler(ContextExceptionV2.class)
    public ResponseEntity<Object> handleException(ContextExceptionV2 ex) {
        return ResponseEntity
                .status(HttpStatus.OK)
                .body(new Result<>(ex.getCode(), ex.getMessage(), null));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception ex, HttpServletRequest request)  {
        logger.error(
                "Error when HTTP request incoming: {} {}?{}, error: {}",
                request.getMethod(),
                request.getRequestURL(),
                request.getQueryString(),
                ex
        );
        if (ex instanceof ContextExceptionV2) {
            ContextExceptionV2 cx = (ContextExceptionV2) ex;
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .body(new Result<>(cx.getCode(), cx.getMsg(), cx.getData()));
        }

        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new Result<>(500, "系统异常，请稍后再试~~", null));
    }

}
